package com.ruoyi.common.verify;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.SneakyThrows;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;

/**
 * 自定义xss校验注解实现
 *
 * @author ruoyi
 */
public abstract class BaseValidator<T extends Annotation, V> implements ConstraintValidator<T, V> {
    public abstract boolean valid(V value, T annotationBean);

    private T annotation;

    @Override
    public void initialize(T constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    public boolean isNotNull(V value) {
        return value instanceof String ? StringUtils.isNotEmpty((String) value) : ObjectUtil.isNotNull(value);
    }

    @Override
    public boolean isValid(V value, ConstraintValidatorContext context) {
        return valid(value, annotation);
    }


    @SneakyThrows
    public static <Q extends BaseValidator> Q getValidator(Class<Q> clazz) {
        return clazz.newInstance();
    }

}
